#include "HelloWorldTopicDataType.h"
//#include <iostream>

HelloWorldTopicDataType::HelloWorldTopicDataType() : TopicDataType()
{
	setName("HelloWorldTopicDataType");
}
HelloWorldTopicDataType::~HelloWorldTopicDataType()
{

}
bool HelloWorldTopicDataType::serialize(DdsCdr& cdr, void *data, std::shared_ptr<SerializedPayload_t> data_value)
{
	HelloWorld* pData = static_cast<HelloWorld*>(data);
	pData->serialize(cdr);
/*
	int errorno = 0;
	char buf[1024] = { };
	cdr.getLastErrorInfo(errorno,buf);
	if (errorno != NO_ERROR)
	{
		std::cout << "cdr serialize fail:" << buf << std::endl;
		return false;
	}
*/
	data_value->length = cdr.getBuf(reinterpret_cast<void**>(&data_value->value));
	return true;
}
bool HelloWorldTopicDataType::deserialize(DdsCdr& cdr, std::shared_ptr<SerializedPayload_t> data_value, void *data)
{
	HelloWorld* pData = static_cast<HelloWorld*>(data);
	cdr.setBuf(reinterpret_cast<void**>(&(data_value->value)), data_value->length);
	pData->deserialize(cdr);
/*
	int errorno = 0;
	char buf[1024] = { };
	cdr.getLastErrorInfo(errorno,buf);
	if (errorno != NO_ERROR)
	{
		std::cout << "cdr deserialize fail:" << buf << std::endl;
		return false;
	}
*/
	return true;
}
// The func of getKey is non-thread-safe
bool HelloWorldTopicDataType::getKey(void* data, InstanceHandle_t* ihandle)
{
	if (!HelloWorld::isKeyDefined())
	{
		return false;
	}
	HelloWorld* pData = static_cast<HelloWorld*>(data);
	unsigned int length;
	char *buf = nullptr;
	pData->serializeKey(&buf,&length);
	if (length > 16)
	{
		gstone::UtilHelper::generate_digest(buf,length,reinterpret_cast<char*>(ihandle->value));
	}
	else
	{
		memcpy(ihandle->value, buf, length);
	}
	if (buf && pData->isKeySerializeByCdr())
	{
		delete buf;
		buf = nullptr;
	}
	return true;
}
bool HelloWorldTopicDataType::getKey(std::shared_ptr<SerializedPayload_t> data_value, InstanceHandle_t* ihandle)
{
	if (!HelloWorld::isKeyDefined())
	{
		return false;
	}
	HelloWorld data;
	DdsCdr cdr;
	deserialize(cdr,data_value,reinterpret_cast<void*>(&data));
	getKey(reinterpret_cast<void*>(&data),ihandle);
	return true;
}
bool HelloWorldTopicDataType::initDataPtr(void* data)
{
	if (data == nullptr)
	{
		return false;
	}
	new(data)HelloWorld;

	return true;
}
bool HelloWorldTopicDataType::isWithKey()
{
	return HelloWorld::isKeyDefined();
}
bool HelloWorldTopicDataType::isPlainTypes()
{
	return HelloWorld::isPlainTypes();
}
void* HelloWorldTopicDataType::createDataResource()
{
	HelloWorld* pData = new HelloWorld;

	return pData;
}
void HelloWorldTopicDataType::releaseDataResource(void *data)
{
	if (data == nullptr)
	{
		return;
	}
	HelloWorld* pData = reinterpret_cast<HelloWorld*>(data);
	delete pData;
	pData = nullptr;
}
